<script setup lang="ts">
import { ref, computed, onMounted, Ref, watch } from 'vue'
import { useTeamStore, useUserStore } from '@/store'
import { Message } from '@arco-design/web-vue'
import { IconPlus, IconSearch } from '@arco-design/web-vue/es/icon'
import {
  BUG_STATUS_CONFIG,
  getCompleteStatus,
  getCompleteColor,
  getCompleteIcon
} from '@/constants/CompleteStatus'
import { PRIORITY_CONFIG, getTaskPriorityColor, getPriorityLabel } from '@/constants/Priority'
import BugCreate from '@/components/bugs/BugCreate.vue'
import dayjs from 'dayjs'
import { pageBugsUsingPost, deleteBugUsingDelete } from '@/api/bugController'
import BugView from '@/components/bugs/BugView.vue'
import type { TableColumnData } from '@arco-design/web-vue'

defineOptions({
  name: 'BugManage'
})

const props = defineProps<{
  proId: number
}>()

const userStore = useUserStore()
const teamStore = useTeamStore()

// 搜索和筛选条件
const searchConfig = ref({
  keyword: ''
})

// 添加筛选状态
const bugFilter = ref('all')

// 分页查询
const pageBugRequest: Ref<API.PageBugRequest> = ref({
  current: 1,
  pageSize: 10,
  proId: props.proId,
  mileId: undefined,
  iterId: undefined,
  reqId: undefined,
  taskId: undefined,
  status: undefined,
  title: undefined,
  ownerId: undefined
})

const BugList: Ref<API.PageBugVo_> = ref({})
const loading = ref(false)

// 分页相关变量
const total = ref<number>(0)
const current = ref<number>(1)
const pageSize = ref<number>(10)

// 获取缺陷列表
const getBugList = async () => {
  loading.value = true
  try {
    // 先获取所有缺陷
    pageBugRequest.value.proId = props.proId
    // 清除筛选条件，获取全部数据
    pageBugRequest.value.ownerId = undefined
    pageBugRequest.value.status = undefined

    const res: any = await pageBugsUsingPost(pageBugRequest.value)
    if (res.code === 0) {
      let filteredRecords = res.data.records

      // 在前端根据条件筛选
      switch (bugFilter.value) {
        case 'my':
          // 我负责的
          filteredRecords = filteredRecords.filter(
            (record: API.BugVo) => record.owner?.id === userStore.user.id
          )
          break
        case 'overdue':
          // 逾期的
          const now = dayjs()
          filteredRecords = filteredRecords.filter(
            (record: API.BugVo) =>
              (record.endTime && dayjs(record.endTime).isBefore(now)) &&
              record.status !== BUG_STATUS_CONFIG.FIXED.value
          )
          break
        case 'today':
          // 今日到期
          filteredRecords = filteredRecords.filter(
            (record: API.BugVo) =>
              dayjs(record.endTime).isSame(dayjs(), 'day') &&
              record.status !== BUG_STATUS_CONFIG.FIXED.value
          )
          break
        case 'week':
          // 本周到期
          filteredRecords = filteredRecords.filter(
            (record: API.BugVo) =>
              dayjs(record.endTime).isSame(dayjs(), 'week') &&
              record.status !== BUG_STATUS_CONFIG.FIXED.value
          )
          break
        default:
          // 全部缺陷，不需要额外筛选
          break
      }

      BugList.value = {
        ...res.data,
        records: filteredRecords
      }
      // 使用过滤后的数据长度作为总数
      total.value = filteredRecords.length
      current.value = Number(res.data.current)
      pageSize.value = Number(res.data.size)
    } else {
      Message.error(res.message || '获取缺陷列表失败')
    }
  } catch (error) {
    console.error('获取缺陷列表失败:', error)
    Message.error('获取缺陷列表失败')
  } finally {
    loading.value = false
  }
}

// 搜索处理函数
const handleSearch = async () => {
  pageBugRequest.value.current = 1
  pageBugRequest.value.title = searchConfig.value.keyword
  await getBugList()
}

// 分页变化处理函数
const handlePageChange = async (page: number) => {
  pageBugRequest.value.current = Number(page)
  await getBugList()
}

// 监听筛选条件变化
watch(bugFilter, () => {
  pageBugRequest.value.current = 1
  getBugList()
})

// 表格列定义
type TableRecord = {
  record: API.BugVo;
  column: TableColumnData;
  rowIndex: number;
}

const columns: TableColumnData[] = [
  {
    title: '缺陷编号',
    dataIndex: 'code',
    width: 80,
    fixed: 'left'
  },
  {
    title: '缺陷标题',
    dataIndex: 'title',
    width: 300,
    fixed: 'left'
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100,
    slotName: 'status'
  },
  {
    title: '优先级',
    dataIndex: 'priority',
    width: 100,
    slotName: 'priority'
  },
  {
    title: '负责人',
    dataIndex: 'owner',
    width: 120,
    slotName: 'owner'
  },
  {
    title: '创建人',
    dataIndex: 'creator',
    width: 120,
    slotName: 'creator'
  },
  {
    title: '开始时间',
    dataIndex: 'startTime',
    width: 180,
    render: ({ record }: TableRecord) => 
      dayjs(record.startTime).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '结束时间',
    dataIndex: 'endTime',
    width: 180,
    render: ({ record }: TableRecord) => 
      dayjs(record.endTime).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '完成时间',
    dataIndex: 'completeTime',
    width: 180,
    render: ({ record }: TableRecord) =>
      record.completeTime ? dayjs(record.completeTime).format('YYYY-MM-DD HH:mm:ss') : '-'
  },
  {
    title: '创建时间',
    dataIndex: 'createAt',
    width: 180,
    render: ({ record }: TableRecord) => 
      dayjs(record.createAt).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '更新时间',
    dataIndex: 'updateAt',
    width: 180,
    render: ({ record }: TableRecord) => 
      dayjs(record.updateAt).format('YYYY-MM-DD HH:mm:ss')
  },
  {
    title: '操作',
    width: 180,
    fixed: 'right',
    slotName: 'operations'
  }
] as TableColumnData[]

// 创建缺陷
const bugCreateVisible = ref(false)
const handleCreateBug = () => {
  bugCreateVisible.value = true
}

// 添加预览包装器
const previewWrapper = ref({
  bugPreviewVisible: false,
  bugPreviewId: null
})

// 添加编辑处理函数
const handleEditBug = (record: any) => {
  previewWrapper.value.bugPreviewVisible = true
  previewWrapper.value.bugPreviewId = record.id
}

// 添加删除处理函数
const handleDeleteBug = async (record: any) => {
  try {
    const res: any = await deleteBugUsingDelete({ bugId: record.id })
    if (res.code === 0) {
      Message.success('删除成功')
      await getBugList() // 重新加载列表
    } else {
      Message.error(res.message || '删除失败')
    }
  } catch (error) {
    Message.error('删除失败')
  }
}

// 添加关闭处理函数
const handleEditClose = async (id: number) => {
  await getBugList() // 重新加载列表
}

// 获取缺陷状态标签
const getBugStatusLabel = (status: number) => {
  const statusConfig = Object.values(BUG_STATUS_CONFIG).find(config => config.value === status)
  return statusConfig?.label || '未知'
}

// 获取缺陷状态颜色
const getBugStatusColor = (status: number) => {
  const statusConfig = Object.values(BUG_STATUS_CONFIG).find(config => config.value === status)
  return statusConfig?.color || 'gray'
}

onMounted(async () => {
  await getBugList()
})
</script>

<template>
  <div class="bug-manage-container">
    <div class="operation-bar">
      <!-- 左侧搜索和筛选 -->
      <div class="left-operations">
        <a-input-search
          v-model="searchConfig.keyword"
          placeholder="搜索缺陷"
          style="width: 200px; margin-right: 16px"
          allow-clear
          @search="handleSearch"
        >
          <template #button-icon>
            <icon-search />
          </template>
        </a-input-search>

        <!-- 筛选按钮组 -->
        <a-radio-group type="button" v-model="bugFilter">
          <a-radio value="all">全部缺陷</a-radio>
          <a-radio value="my">我负责的</a-radio>
          <a-radio value="overdue">已逾期</a-radio>
          <a-radio value="today">今日到期</a-radio>
          <a-radio value="week">本周到期</a-radio>
        </a-radio-group>
      </div>

      <!-- 右侧创建按钮 -->
      <div class="right-operations">
        <a-button type="primary" @click="handleCreateBug">
          <template #icon>
            <icon-plus />
          </template>
          BUG
        </a-button>
      </div>
    </div>

    <div class="table-container">
      <a-table
        :columns="columns"
        :data="BugList.records"
        :loading="loading"
        :scroll="{ x: 1600, y: '100%' }"
        :pagination="{
          total: Number(total),
          current: Number(current),
          pageSize: Number(pageSize),
          showTotal: true,
        }"
        @page-change="handlePageChange"
      >
        <!-- 状态列插槽 -->
        <template #status="{ record }">
          <a-tag :color="getBugStatusColor(record.status)">
            {{ getBugStatusLabel(record.status) }}
          </a-tag>
        </template>

        <!-- 优先级列插槽 -->
        <template #priority="{ record }">
          <a-tag :color="getTaskPriorityColor(record.priority)">
            {{ getPriorityLabel(record.priority) }}
          </a-tag>
        </template>

        <!-- 负责人列插槽 -->
        <template #owner="{ record }">
          <a-avatar :size="24" :image-url="record.owner?.avatar">
            {{ record.owner?.nickname?.[0] || record.owner?.username?.[0] }}
          </a-avatar>
          <span class="owner-name">{{ record.owner?.nickname || record.owner?.username }}</span>
        </template>

        <!-- 创建人列插槽 -->
        <template #creator="{ record }">
          <a-avatar :size="24" :image-url="record.creator?.avatar">
            {{ record.creator?.nickname?.[0] || record.creator?.username?.[0] }}
          </a-avatar>
          <span class="creator-name">{{
            record.creator?.nickname || record.creator?.username
          }}</span>
        </template>

        <!-- 操作列插槽 -->
        <template #operations="{ record }">
          <a-space>
            <a-button type="text" size="small" @click="handleEditBug(record)"> 编辑 </a-button>
            <a-popconfirm content="确定删除该缺陷吗？" @ok="handleDeleteBug(record)">
              <a-button type="text" status="danger" size="small"> 删除 </a-button>
            </a-popconfirm>
          </a-space>
        </template>
      </a-table>
    </div>

    <!-- 缺陷创建弹窗 -->
    <BugCreate
      v-if="bugCreateVisible"
      :visible="bugCreateVisible"
      :proId="Number(proId)"
      @update:visible="(val) => (bugCreateVisible = val)"
      @reload="handleSearch"
    />

    <!-- 添加 BugView 组件 -->
    <BugView
      v-if="previewWrapper.bugPreviewVisible"
      :visible="previewWrapper.bugPreviewVisible"
      :bugId="Number(previewWrapper.bugPreviewId)"
      @update:visible="(val) => (previewWrapper.bugPreviewVisible = val)"
      @close="handleEditClose"
    />
  </div>
</template>

<style scoped>
.bug-manage-container {
  height: 100%;
  display: flex;
  flex-direction: column;
  padding: 16px;
  background-color: var(--color-bg-1);
}

.operation-bar {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 16px;
}

.left-operations {
  display: flex;
  align-items: center;
  gap: 16px;
}

.right-operations {
  display: flex;
  gap: 8px;
  align-items: center;
}

.table-container {
  flex: 1;
  overflow: hidden;
  background-color: var(--color-bg-2);
  border-radius: 4px;
  box-shadow: 0 2px 5px rgba(0, 0, 0, 0.1);
}

.owner-name,
.creator-name {
  margin-left: 8px;
  font-size: 14px;
}

:deep(.arco-table-th) {
  background-color: var(--color-fill-2) !important;
}

:deep(.arco-table-tr:hover) {
  background-color: var(--color-fill-2);
}

:deep(.arco-input-search) {
  width: 320px;
}

/* 添加缺陷编号样式 */
:deep(.arco-table-cell-code) {
  font-family: Monaco, Consolas, monospace;
  color: var(--color-text-2);
  font-size: 13px;
}
</style>
